package com.wyp168.service.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.wyp168.commonutils.R;
import com.wyp168.service.vod.service.VodService;
import com.wyp168.service.vod.utils.ConstantPropertiesUtils;
import com.wyp168.service.vod.utils.InitObject;
import com.wyp168.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    VodService vodService;

    //上传视频到阿里云
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file) throws IOException {
        String videoId = vodService.uploadVideo(file);
        System.out.println(videoId);
        return R.ok().data("videoId",videoId);
    }

    //获取视频名称
    @GetMapping("getVideoName/{videoId}")
    public R getVideoName(@PathVariable String videoId) {
        String videoName = vodService.getVideoNameById(videoId);
        return R.ok().data("videoName",videoName);
    }


    //根据视频id删除阿里云中视频
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id) {
        vodService.removeVideo(id);
        return R.ok();
    }

    //根据视频id集合批量删除阿里云中视频
    @DeleteMapping("deleteBatchVideo")
    public R deleteBatchVideo(@RequestParam("videoIds") String videoIds) {
        vodService.deleteBatchVideo(videoIds);
        return R.ok();
    }


    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            //创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
            //创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

            //向request中设置视频id
            request.setVideoId(id);

            GetVideoPlayAuthResponse response = client.getAcsResponse(request);

            String playAuth = response.getPlayAuth();

            System.out.println("****视频id为： " + id);
            System.out.println("获取到的凭证为： "  + playAuth);

            return R.ok().data("playAuth",playAuth);
        } catch (ClientException e) {
            throw new GuliException(20001,"获取凭证失败");
        }


    }
}
